<?php

class AdminController extends Zend_Controller_Action 
{
    protected $paper;
    protected $review;
    protected $participant;
	protected $assignment;
    protected $user;
	public function preDispatch(){
		if (Zend_Auth::getInstance()->hasIdentity()) {
			$this->user = Zend_Auth::getInstance()->getIdentity(); 
            if(!in_array($this->user->email, Zend_Registry::get('admins'))){
                $this->_forward('index', 'login');
            }
		}else{
			$this->_forward('index', 'login');
		}
	}
	public function init()
    {
        $ajaxContext = $this->_helper->getHelper('AjaxContext');
        $ajaxContext->addActionContext('view', 'html')
                    ->addActionContext('comment', 'html')                    
                    ->initContext();
    }
    public function indexAction(){
    	
    }
    public function reviewsAction(){
    }
    public function assignmentsAction(){
    }
    public function assignAction(){
    	$request = $this->getRequest();
		if($request->isPost()){
			$r_list = explode(':', $request->getParam('rList'));
			$p_list = explode(':', $request->getParam('pList'));            
			$as = $this->getAssignment();
			$assigned = $as->assignPapers($r_list, $p_list);
			$paper = $this->getPaper();
			$paper->setAssigned($assigned, true);
			die();	
		}		
    }
	
	public function cancelassignmentsAction(){
    	$request = $this->getRequest();
		if($request->isPost()){
			$a_list = explode(':', $request->getParam('a_list'));
			$as = $this->getAssignment();
            $as->cancelAssignments($a_list);
			die();	
		}		
    }
	public function notifyAction(){
    	$request = $this->getRequest();
		if($request->isPost()){
			$a_list = explode(':', $request->getParam('a_list'));
			$r_list = explode(':', $request->getParam('r_list'));
			$as = $this->getAssignment();
            $as->notifyAssignments($a_list, $r_list);
			foreach($r_list as $r){
				$this->notificationMail($r);
			}
			die();	
		}		
    }	
	public function unassignedAction(){
		$request = $this->getRequest();
   		$callback = $request->getParam('callback');
        $paper = $this->getPaper();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');
        /*$start = $request->getParam('start');
        $limit = $request->getParam('limit');*/
		$area_id = $request->getParam('area_id');
		$res = $paper->getUnassigned($area_id, $sort, $dir);//, $limit, $start);
     	$count = count($res);//$paper->getUnassignedCount($area_id);
        $json = array();
        $json['totalCount'] = $count;
        $json['unassigned'] = $res;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
	public function assignedAction(){
		$request = $this->getRequest();
   		$callback = $request->getParam('callback');
        $paper = $this->getPaper();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');
   /*     $start = $request->getParam('start');
        $limit = $request->getParam('limit');*/
		$area_id = $request->getParam('area_id');
		$res = $paper->getAssigned($area_id, $sort, $dir);//, $limit, $start);
     	$count = $paper->getAssignedCount($area_id);
        $json = array();
        $json['totalCount'] = $count;
        $json['assigned'] = $res;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
	public function reviewersAction(){
		$request = $this->getRequest();
   		$callback = $request->getParam('callback');
        $p = $this->getParticipant();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');
        $start = $request->getParam('start');
        $limit = $request->getParam('limit');
		$res = $p->getReviewers($sort, $dir, $limit, $start);
     	$count = $p->getReviewersCount();
        $json = array();
        $json['totalCount'] = $count;
        $json['reviewers'] = $res;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}    
	public function getpapersAction(){
		$request = $this->getRequest();
    	$callback = $request->getParam('callback');
        $model = $this->getPaper();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');        
        $filter = $request->getParam('filter');
     	//$count = $total = $model->getTotalFilter($filter);        
        $papers_temp = $model->getPapersFilter($sort, $dir, $filter);
        $c = count($papers_temp);
        $papers = array();
        for($i = 0; $i < $c; $i++){
            $file_pdf = $papers_temp[$i]['file_pdf'];
            $file_doc = $papers_temp[$i]['file_doc'];
            if($file_pdf != ''){
                @$papers_temp[$i]['file_size_pdf'] = round(filesize(PDF_FILES_PATH . $file_pdf) / 1024, 2);
            }else{
                $papers_temp[$i]['file_size_pdf'] = 0;
            }
            if($file_doc != ''){
                @$papers_temp[$i]['file_size_doc'] = round(filesize(DOC_FILES_PATH . $file_doc) / 1024, 2);
            }else{
                $papers_temp[$i]['file_size_doc'] = 0;
            }
            $papers[$i] = $papers_temp[$i];
        }
        $json = array();
        $json['totalCount'] = $c;
        $json['papers'] = $papers;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
    public function reviewedpapersAction(){
		$request = $this->getRequest();
    	$callback = $request->getParam('callback');
        $model = $this->getPaper();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');        
        $filter = $request->getParam('filter');
     	//$count = $total = $model->getTotalFilter($filter);        
        $papers_temp = $model->getReviewedPapers($sort, $dir, $filter);
        $c = count($papers_temp);
        $papers = array();
        for($i = 0; $i < $c; $i++){
            $file_pdf = $papers_temp[$i]['file_pdf'];
            $file_doc = $papers_temp[$i]['file_doc'];
            if($file_pdf != ''){
                @$papers_temp[$i]['file_size_pdf'] = round(filesize(PDF_FILES_PATH . $file_pdf) / 1024, 2);
            }else{
                $papers_temp[$i]['file_size_pdf'] = 0;
            }
            if($file_doc != ''){
                @$papers_temp[$i]['file_size_doc'] = round(filesize(DOC_FILES_PATH . $file_doc) / 1024, 2);
            }else{
                $papers_temp[$i]['file_size_doc'] = 0;
            }
            $papers[$i] = $papers_temp[$i];
        }
        $json = array();
        $json['totalCount'] = $c;
        $json['papers'] = $papers;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
    public function getassignmentsAction(){
		$request = $this->getRequest();
    	$callback = $request->getParam('callback');
        $model = $this->getAssignment();
		$sort = $request->getParam('sort');
		$dir = $request->getParam('dir');        
        $filter = $request->getParam('filter');     	
        $assignments = $model->getAssignments1($sort, $dir);
        $c = count($assignments);
		$json = array();
        $json['totalCount'] = $c;
        $json['assignments'] = $assignments;
        echo $callback.'('.Zend_Json::encode($json).')';
        die();
	}
    public function updatepaperAction(){
        $request = $this->getRequest();
		if($request->isPost()){			
            $data = $request->getParams();                    
            $newpaper = array();
            $newpaper['id'] = $data['id'];
            $newpaper['area_id'] = $data['area_id'];
            $newpaper['category_id'] = $data['category_id'];
            if(isset($data['isActive'])){
                $newpaper['isActive'] = 1;
            }else{
                $newpaper['isActive'] = 0;
            }
			$paper = $this->getPaper();
            $paper->save($newpaper);
			die();	
		}		
    }
    public function updatestatusAction(){
        $request = $this->getRequest();
		if($request->isPost()){			
            $data = $request->getParams();                    
            $newpaper = array();
            $newpaper['id'] = $data['paper_id'];
            $newpaper['status_id'] = $data['status_id'];                        
			$paper = $this->getPaper();
            $paper->save($newpaper);
			die();	
		}
    }
    protected function getPaper()
    {
        if (null === $this->paper) {
            require_once APPLICATION_PATH . '/models/Paper.php';
            $this->paper = new Model_Paper();
        }
        return $this->paper;
    }
	protected function getAssignment()
    {
        if (null === $this->assignment) {
            require_once APPLICATION_PATH . '/models/Assignment.php';
            $this->assignment = new Model_Assignment();
        }
        return $this->assignment;
    }
	protected function getParticipant()
    {
        if (null === $this->participant) {
            require_once APPLICATION_PATH . '/models/Participant.php';
            $this->participant = new Model_Participant();
        }
        return $this->participant;
    }
    protected function getReview()
    {
        if (null === $this->review) {
            require_once APPLICATION_PATH . '/models/Review.php';
            $this->review = new Model_Review();
        }
        return $this->review;
    }
    private function getAreas(){
				require_once APPLICATION_PATH . '/models/Area.php';
      	$model = new Model_Area();
      	return $model->fetchEntries();
    }   
	
	function notificationMail($email){
        $subject = 'ETAI - Papers awaiting for review';
 		$link_mk = $this->view->url(array('language' => 'mk', 'controller' => 'review','action' => 'assigned'), 'default', true);
		$message = '';
		$message .= '<p>Почитувани,<br/>Ве известуваме дека ви се доделени нови трудови за рецензија.</p>';
		$message .= '<p>Кликнете на следниот линк за да ги превземете трудовите, откако претходно ќе се најавите.</p>';
		$message .= '<p><a href="' . SERVER_HOST . $link_mk . '">' . SERVER_HOST . $link_mk . '</a></p>';
		$message .= '<p>По прегледот на трудот, оценката и коментарите за иститиот ве молиме внесете ги во формата за рецензија следејќи го линкот рецензирај труд.</p>';
 	
		$message .= '<br/><br/><hr/><br/><br/>';
		
		$link_en = $this->view->url(array('language' => 'en', 'controller' => 'review','action' => 'assigned'), 'default', true);
		
		$message .= '<p>Respected ETAI 2009 reviewer,<br/>Please be informed that you have new paper(s) awaiting your review.</p>';
		$message .= '<p>You can download the paper(s) by folowing the link (after logging in).</p>';
		$message .= '<p><a href="' . SERVER_HOST . $link_en . '">' . SERVER_HOST . $link_en . '</a></p>';
		$message .= '<p>Please enter your opinion about the paper in the on-line form accesable by following the link Review Paper</p>';
			
        $mail = new Zend_Mail('utf-8');
        $mail->setBodyHtml($message)
            ->setFrom('admin@etai.feit.ukim.edu.mk', 'ETAI - Paper Submition System')
            ->addTo($email)
            ->setSubject($subject)
            ->send();		
        //echo $message;
    }  
   
}
